var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];

//配置MySql数据库
var db = {};

if (config.use_env_variable) {
    var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
    var mysql = new Sequelize(config.mysql.database, config.mysql.username, config.mysql.password, config.mysql);
}

fs.readdirSync(__dirname)
    .filter(function (file) {
        return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
    })
    .forEach(function (file) {
        var model = mysql['import'](path.join(__dirname, file));
        db[model.name] = model;
    });

Object.keys(db).forEach(function (modelName) {
    if (db[modelName].associate) {
        db[modelName].associate(db);
    }
});

db.mysql = mysql;
db.Sequelize = Sequelize;

//配置存放token的存储结构
var tokenCache =  {

    tokens:new Map(),

    /**
     * 获取token
     * @param key 登录名
     * @returns {*}
     */
    getLoginToken:function (login_name) {
     return this.tokens.get(login_name);
    },

    /**
     * 存token到集合
     * @param key 登录名
     * @param value
     */
    putLoginToken:function (login_name, token) {
        this.tokens.set(login_name,token);
    },

    /**
     * 从集合移除token
     * @param key 登录名
     */
    removeLoginToken:function (login_name) {
        this.tokens.delete(login_name);
    },

    /**
     * 判断当前用户是否登录
     * @param login_name
     */
    exists:function (token) {
        var flag = false
        for(let t of this.tokens.values()){
            if(t == token){
                flag = true;
                break;
            }
        }
        return flag;
    }

}

db.tokenCache = tokenCache;

module.exports = db;
